package com.welike.shibo.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.welike.shibo.eneity.Zan;
import com.welike.shibo.exception.BaseException;
import com.welike.shibo.mapper.ZanMapper;
import com.welike.shibo.service.ZanService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author fangyu
 * @version v1.0.0
 * @since 2019-08-20 00:40
 */
@Service
public class ZanServiceImpl extends ServiceImpl<ZanMapper, Zan> implements ZanService {

    @Autowired
    private ZanMapper zanMapper;

    /**
     * 查询数据库是否有这条点赞记录
     * @param userId 用户id
     * @param zanObjId 被赞对象id
     * @return 查询结果 => 数据id
     */
    @Override
    public String queryIdByUserIdAndZanObjId(String userId, String zanObjId) {
        return zanMapper.queryIdByUserIdAndZanObjId(userId, zanObjId);
    }

    /**
     *
     * @param zanType 赞类型 视频点赞=1, 评论点赞=2
     * @param uid 用户id
     * @param objId 被赞对象id
     * @return 返回 true: 成功点赞 false: 成功取消点赞
     */
    @Override
    public Boolean zanOrCancelZan(int zanType, String uid, String objId) {
        Zan zan = new Zan();
        // 先查询数据库有没有点过赞，点过则返回
        if (StringUtils.isBlank(uid) || StringUtils.isBlank(objId)){
            throw new BaseException(404, "参数不可为空");
        }
        String result = this.queryIdByUserIdAndZanObjId(uid, objId);
        // 如果查询结果不为null, 则已经点赞, 从数据库删除点赞记录, 并返回false
        if (result != null){
            this.removeById(result);
            return false;
        }
        // 反之查询结果为null => 即未点赞状态, 则新增点赞数据并插入数据库, 返回true
        zan.setUserId(uid);
        zan.setZanType(zanType);
        zan.setZanObjId(objId);
        zan.setCreateTime(new Date());
        this.save(zan);
        return true;
    }

    // 查询赞的次数通过对象id
    @Override
    public Integer countByZanObjId(String zanObjId) {
        return zanMapper.countByZanObjId(zanObjId);
    }

    // 查看所有赞的次数
    @Override
    public Integer countByZan() {
        return zanMapper.countByZan();
    }

    @Override
    public IPage<Zan> queryZanInVidList(Page page, List<String> vidList) {
        return zanMapper.queryZanInVidList(page, vidList);
    }


}
